//
//  ViewController.m
//  省份城市列表
//
//  Created by 伍银荣 on 2021/6/17.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ViewController.h"
#import "ProvinceModel.h"

@interface ViewController ()<UIPickerViewDelegate, UIPickerViewDataSource>
@property (strong, nonatomic) IBOutlet UIPickerView *pickView;
@property (strong, nonatomic) IBOutlet UILabel *provinceLbl;
@property (strong, nonatomic) IBOutlet UILabel *cityLbl;

@property (nonatomic, strong) NSArray *provinceArr;

//保存当前选中的省的数据
@property (nonatomic, strong) ProvinceModel *proModel;

@end

@implementation ViewController

-(NSArray *)provinceArr {
    if (!_provinceArr) {
        NSArray *arr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"province.plist" ofType:nil]];
        NSMutableArray *mArr = [NSMutableArray array];
        for (NSDictionary *dict in arr) {
            ProvinceModel *model = [ProvinceModel provinceWithDict:dict];
            [mArr addObject:model];
        }
        _provinceArr = mArr;
    }
    return _provinceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pickView.delegate = self;
    self.pickView.dataSource = self;
    [self pickerView:self.pickView didSelectRow:0 inComponent:0];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArr.count;
    } else {
        //获取当前选中的第0组的省的索引
        NSInteger selPrpIdx = [pickerView selectedRowInComponent:0];
        ProvinceModel *proModel = self.provinceArr[selPrpIdx];
        self.proModel = proModel;
        return self.proModel.cities.count;
    }
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArr[row] name];
    } else {
 //       NSInteger selProIdx = [pickerView selectedRowInComponent:0];
//        ProvinceModel *proModel = self.provinceArr[selProIdx];
        return self.proModel.cities[row];
    }
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
       //刷新第一组
        [self.pickView reloadComponent:1];
        [self.pickView selectRow:0 inComponent:1 animated:YES];
    }
  //  NSInteger selProIdx = [pickerView selectedRowInComponent:0];
    NSInteger selCityIdx = [pickerView selectedRowInComponent:1];
   // ProvinceModel *model = self.provinceArr[selProIdx];
    self.provinceLbl.text = self.proModel.name;
    self.cityLbl.text = self.proModel.cities[selCityIdx];
}


@end
